package com.example.learning.demo.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * ClassName Client
 * Description
 *
 * @author <a href="mailto:xuxb@zjport.gov.cn">xuxb</a>
 * @date 2021/5/29 21:27
 * @since 1.0
 */
public class Client {
    private static Selector selector;
    private static int read = 1;
    private static int write = 1;
    public static void main(String[] args) throws IOException {
        selector = Selector.open();
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        socketChannel.connect(new InetSocketAddress(8000));
        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                try {
                    if (selectionKey.isConnectable()) {
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        if (channel.isConnectionPending()) {
                            channel.finishConnect();
                            System.out.println("连接Server成功。。。。。。");
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            buffer.put("我是客户端，感谢提供服务。。。".getBytes());
                            buffer.flip();
                            channel.write(buffer);
                            channel.register(selector, SelectionKey.OP_READ);
                        }
                    }
                    if (selectionKey.isReadable()) {
                        handlerRead(selectionKey);
                    }
                    if (selectionKey.isWritable()) {
                        handlerWrite(selectionKey);
                    }
                }catch (Exception e){
                    selectionKey.cancel();
                    e.printStackTrace();
                }
            }
        }
    }

    private static void handlerRead(SelectionKey selectionKey){
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            channel.read(buffer);
            System.out.println("从服务端接收到消息："+new String(buffer.array())+read);
            channel.register(selector, SelectionKey.OP_WRITE);
            read++;
        }catch (IOException e){
            System.out.println(e.getMessage());
            selectionKey.cancel();
            try {
                channel.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    private static void handlerWrite(SelectionKey selectionKey){
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        try {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put(("好消息"+write).getBytes());
            buffer.flip();
            channel.write(buffer);
            channel.register(selector, SelectionKey.OP_READ);
            write++;
        } catch (IOException e) {
            System.out.println(e.getMessage());
            selectionKey.cancel();
            try {
                channel.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

    }
}
